package com.dq.service.set.impl;

import com.dq.context.Constant;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.GiftGrantSetRecordQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.base.AbstractEntity;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.org.Org;
import com.dq.domain.record.GiftGrantRecord;
import com.dq.domain.setup.GiftGrantSet;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.set.GiftGrantSetRecordService;
import com.dq.utils.BeanNullUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2019/12/30 13:55
 */
@Service
public class GiftGrantSetRecordServiceImpl extends BaseRepositories implements GiftGrantSetRecordService {
    @Override
    public Vo list(GiftGrantSetRecordQuery giftGrantSetRecordQuery) throws AdminException {
        SysUser sysUser = shiroService.getUser();
        giftGrantSetRecordQuery.format();
        Map<String, Object> query = giftGrantSetRecordQuery.parseMap();
        if(sysUser.getSection() != null){
            query.put("org_id",sysUser.getSection().getId());
            query.remove("orgId");
        }
        if(StringUtils.isNotEmpty(giftGrantSetRecordQuery.getCardNo())){
            query.put("sysUser_cardNo"+ BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(giftGrantSetRecordQuery.getCardNo()));
            query.remove("cardNo");
        }
        if(StringUtils.isNotEmpty(giftGrantSetRecordQuery.getUserRealName())){
            query.put("sysUser_userRealcName"+BaseDaoImpl.likeSqlStr,BaseAdminQuery.likeSql(giftGrantSetRecordQuery.getUserRealName()));
            query.remove("userRealName");
        }
        if(giftGrantSetRecordQuery.getGiftGrantSetId() != null){
            query.put("giftGrantSet_id",giftGrantSetRecordQuery.getGiftGrantSetId());
            query.remove("giftGrantSetId");
        }
        if(giftGrantSetRecordQuery.getBeginTime()!=null){
            query.put("createTime"+ BaseDaoImpl.gteSqlStr, giftGrantSetRecordQuery.getBeginTime());
            query.remove("beginTime");
        }
        if(giftGrantSetRecordQuery.getEndTime()!=null){
            query.put("createTime"+ BaseDaoImpl.lteSqlStr, giftGrantSetRecordQuery.getEndTime());
            query.remove("endTime");
        }
        List<GiftGrantRecord> giftGrantSets = dao.find(dao.query2Hql(GiftGrantRecord.class,query),query);
        Long count = dao.count(dao.count2Hql(GiftGrantRecord.class,query),query);
        PageHelper.startPage(giftGrantSetRecordQuery.getPage(),giftGrantSetRecordQuery.getSize());
        PageInfo pageInfo = new PageInfo((List<GiftGrantRecord.Vo>) VO.toVOCollection(giftGrantSets));
        pageInfo.setTotal(count);
        return new Vo(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Vo add(GiftGrantRecord giftGrantRecord,Long giftGrantSetId) throws AdminException {
        SysUser sysUser = shiroService.getUser();
        if(giftGrantRecord.getUserId().size() <= 0){
            throw new AdminException("请选择人员");
        }
        GiftGrantSet giftGrantSet = dao.get(GiftGrantSet.class,giftGrantSetId);
        if(giftGrantSet == null){
            throw new AdminException("请选择类别");
        }
        List<GiftGrantRecord> list = new ArrayList<>();
        for (Long userId: giftGrantRecord.getUserId()) {
            GiftGrantRecord g = new GiftGrantRecord();
            g.setGrantCategory(giftGrantRecord.getGrantCategory());
            g.setGiftGrantSet(giftGrantSet);
            g.setGrantNum(giftGrantRecord.getGrantNum());
            g.setCostPrice(giftGrantRecord.getCostPrice());
            g.setDescription(giftGrantRecord.getDescription());
            SysUser user = dao.get(SysUser.class,userId);
            g.setSysUser(user);
            g.setOrg((Org) sysUser.getSection());
            g.setGiftGrantNo(AbstractEntity.generyDatetimeAndRandomNum(Constant.ORDERS_SUFF_COUNT));

            g.setCreateUser(sysUser);
            g.setUpdateUser(sysUser);
            g.setCreateTime(System.currentTimeMillis());
            g.setLastModifyTime(System.currentTimeMillis());
            g.setVersion(Constant.VERSION_VALUE);
            list.add(g);
        }
        if(giftGrantSet.getStock() == null){
            giftGrantSet.setStock(0L);
        }
        Long stock = giftGrantSet.getStock()-list.size()*giftGrantRecord.getGrantNum();
        if(stock < 0){
            throw new AdminException("礼物数量不足");
        }
        giftGrantSet.setStock(stock);
        giftGrantSetRepository.save(giftGrantSet);
        giftGrantSetRecordRepository.saveAll(list);
        return new Vo(HttpStatus.OK);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Vo edit(GiftGrantRecord giftGrantRecordEdit,Long id,Long giftGrantSetId) throws AdminException {
        SysUser sysUser = shiroService.getUser();
        GiftGrantRecord giftGrantRecord = dao.get(GiftGrantRecord.class,id);
        if(giftGrantRecord == null){
            throw new AdminException("请重新选择");
        }
        GiftGrantSet giftGrantSet = dao.get(GiftGrantSet.class,giftGrantSetId);
        if(giftGrantSet == null){
            throw new AdminException("请选择类别");
        }
        giftGrantRecordEdit.setUpdateUser(sysUser);
        giftGrantRecordEdit.setLastModifyTime(System.currentTimeMillis());
        if(giftGrantRecord.getGrantNum() != giftGrantRecordEdit.getGrantNum()){
            //增加数量
            if(giftGrantRecord.getGrantNum() < giftGrantRecordEdit.getGrantNum()){
                Long num = giftGrantRecordEdit.getGrantNum() - giftGrantRecord.getGrantNum();
                Long stock = giftGrantSet.getStock() - num;
                if(stock < 0){
                    throw new AdminException("礼物数量不足");
                }
                giftGrantSet.setStock(stock);
            }else {
                Long num = giftGrantRecord.getGrantNum() - giftGrantRecordEdit.getGrantNum();
                Long stock = giftGrantSet.getStock() + num;
                giftGrantSet.setStock(stock);
            }
            giftGrantSetRepository.save(giftGrantSet);
        }
        BeanUtils.copyProperties(giftGrantRecordEdit,giftGrantRecord, BeanNullUtil.getNullPropertyNames(giftGrantRecordEdit));
        giftGrantSetRecordRepository.save(giftGrantRecord);
        return new Vo(HttpStatus.OK);
    }

    @Override
    public Vo delete(Long id) throws AdminException {
        GiftGrantRecord giftGrantRecord = dao.get(GiftGrantRecord.class,id);
        if(giftGrantRecord == null){
            throw new AdminException("请重新选择");
        }
        giftGrantRecord.setDeleted(true);
        giftGrantSetRecordRepository.save(giftGrantRecord);
        return new Vo(HttpStatus.OK);
    }
}
